package org.zjx.action.start;

import com.sun.jna.platform.win32.WinDef;
import lombok.SneakyThrows;
import org.zjx.action.Action;
import org.zjx.action.basic.DelayAction;
import org.zjx.core.IWindow;
import org.zjx.core.impl.StartWindow;
import org.zjx.util.HwndUtil;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import java.util.List;

public class OpenWindowAction extends Action {

    // 常量定义
    private static final String WINDOW_CLASS_LAUNCHER = "#32770";
    private static final String GAME_TITLE = "梦幻西游 ONLINE";

    public OpenWindowAction(IWindow targetWindow) {
        super(targetWindow, false);
    }

    @Override
    protected void doExecute() {
        List<WinDef.HWND> existingGameWindows = HwndUtil.findWindows(WINDOW_CLASS_LAUNCHER, GAME_TITLE);
        if (existingGameWindows.isEmpty()) {
            openWindow();
            targetWindow.submitAction(new DelayAction(targetWindow,3000));
        }else {
            targetWindow.setHwnd(existingGameWindows.get(0));
        }
    }

    @SneakyThrows
    public void openWindow() {
        String gameExePath = ((StartWindow)targetWindow).getGameExePath();
        File gameFile = new File(gameExePath);
        if (!gameFile.exists()) {
            throw new IOException("游戏可执行文件不存在: " + gameExePath);
        }

        Desktop.getDesktop().open(gameFile);
    }
}
